var appid = 'kou72um0ioak1kubrz0klwx8a7s3l261mgt54vbyotnblnby';
var appkey = 'o56bexx1vr522x7ygfkvi7efvbhhmo6x2oaf3txb75wi2509';
AV.initialize(appid, appkey);
Frame = AV.Object.extend('Frame');
Topic = AV.Object.extend('Topic');
var shares = {};
var frame_id;
var storage = window.localStorage;

function hasClass(obj, cls) {
	return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(obj, cls) {
	if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}

function removeClass(obj, cls) {
	if (hasClass(obj, cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
		obj.className = obj.className.replace(reg, ' ');
	}
}

var load_video = function(url, ele) {
	ele.removeAttribute('data-src');
	mui.getJSON('http://t.fanheapp.com/get_video', {
		url: url
	}, function(response) {
		if (response.success) {
			var video_url = response.data.video;
			ele.setAttribute('src', video_url);
		} else {
			console.log('load error for url:' + url);
		}
	});
}

var refresh_src = function() {
	mui("video").each(function() {
		var url = this.getAttribute('data-src');
		var src = this.getAttribute('src');
		if (url) {
			console.log("Load Video Url: " + url)
			load_video(url, this);
		}
	});
}

mui.init({
	swipeBack: true,
});
mui.plusReady(function() {
	plus.nativeUI.showWaiting();
	var screen_width = plus.screen.resolutionWidth;
	var args = plus.webview.currentWebview();
	frame_id = args.frame_id;
	//var frame_id = '566802f000b07a180e03c5bc';
	var storage_key = 'frame_' + frame_id;
	if (storage_key in storage) {
		var frame_data = JSON.parse(storage[storage_key]);
		frame_data['width'] = screen_width;
		var frame_html = template('frame', frame_data);
		document.getElementById("frame-content").innerHTML = frame_html;
		refresh_src();
		setTimeout(function() {
			plus.nativeUI.closeWaiting();
		}, 200);
	}
	
	var frame = new Frame();
	frame.id = frame_id;
	frame.fetch().then(function(frame) {
		topic_id = frame.get("topic");
		var meta_data_string = frame.get('metaDataV2');
		var meta_data = JSON.parse(meta_data_string);
		var frame_data = {
			id: frame.id,
			url: frame.get('url'),
			rec: frame.get('title'),
			cover: frame.get('coverUrl'),
			type: meta_data['type'],
			title: meta_data['text'],
			author: meta_data['author'],
			avatar: meta_data['avatarUrl'],
			source: meta_data['source'],
			content: meta_data['content'],
		};
		if(!(storage_key in storage)){
			frame_data['width'] = screen_width;
			var frame_html = template('frame', frame_data);
			document.getElementById("frame-content").innerHTML = frame_html;
			refresh_src();
			setTimeout(function() {
				plus.nativeUI.closeWaiting();
			}, 200);
		}
		storage[storage_key] = JSON.stringify(frame_data);
	}, function(error) {
		console.log(error.message);
	});

	//搞定分享列表
	plus.share.getServices(function(s) {
		if (s && s.length > 0) {
			for (var i = 0; i < s.length; i++) {
				var t = s[i];
				//使用id作为key
				shares[t.id] = t;
				console.log(i + ":" + t.id);
			}
		}
	}, function() {
		console.log("获取分享服务列表失败");
	});
});

var is_hide = false;
mui('body').on('tap', '#share-btn', function() {
	if (!is_hide) {
		mui('#share').popover('toggle');
	}
});

//document.body.addEventListener("dragup", function(e) {
//	if (!is_hide) {
//		var eles = document.getElementsByClassName('down-hide');
//		for (var i = 0; i < eles.length; i++) {
//			removeClass(eles[i], 'fadein');
//			addClass(eles[i], 'fadeout');
//		}
//		is_hide = true;
//		removeClass(mui('#back-btn')[0], 'mui-action-back');
//	}
//}, false);
//
//document.body.addEventListener("dragdown", function(e) {
//	if (is_hide) {
//		var eles = document.getElementsByClassName('down-hide');
//		for (var i = 0; i < eles.length; i++) {
//			removeClass(eles[i], 'fadeout');
//			addClass(eles[i], 'fadein');
//		}
//		is_hide = false;
//		addClass(mui('#back-btn')[0], 'mui-action-back');
//	}
//}, false);

mui('#share').on('tap', 'img', function() {
	//DQ：Maybe 提前缓存好？
	var id = this.getAttribute('data-id');
	var type = this.getAttribute('data-type');
	var frame = new Frame();
	frame.id = self.frame_id;
	console.log(frame_id)
	frame.fetch().then(function(f) {
		var msg = {};
		//TODO: 这里都需要再考虑一下
		msg.title = f.get("head");
		msg.content = f.get("content");
		msg.href = "http://t.fanheapp.com/app_topic/" + f.get("topic").id + "?frame="+f.id;
		msg.thumbs = ["_www/img/miao_120.png"]

		console.log(JSON.stringify(msg));

		if (type == "link") {
			mui('#share').popover('toggle');
			//TODO
			mui.toast("链接已复制到剪贴板");
			return;
		}

		if (type == "weixin-session") {
			msg.extra = {
				scene: "WXSceneSession"
			}
		}
		if (type == "weixin-timeline") {
			msg.extra = {
				scene: "WXSceneTimeline"
			}
		}
		var share = shares[id];
		if (share) {
			if (share.authenticated) {
				console.log("正在分享到" + share.description);
				share.send(msg, function() {
					mui('#share').popover('toggle');
					mui.toast("分享到" + share.description + "成功");
				}, function(e) {
					mui('#share').popover('toggle');
					mui.toast("分享到" + share.description + "失败");
					console.log("分享到\"" + share.description + "\"失败: " + e.code + " - " + e.message);
				});
			} else {
				share.authorize(function() {
					share.send(msg, function() {
						mui('#share').popover('toggle');
						mui.toast("分享到" + share.description + "成功！ ");
					}, function(e) {
						mui('#share').popover('toggle');
						mui.toast("分享到" + share.description + "失败");
						console.log("分享到\"" + share.description + "\"失败: " + e.code + " - " + e.message);
					});
				}, function(e) {
					mui('#share').popover('toggle');
					mui.toast("认证授权失败" + e.message);
					console.log("认证授权失败：" + e.code + " - " + e.message);
				});
			}
		} else {
			mui.toast("无法获取分享服务");
		}
	}, function(error) {
		console.log('error when fetch almanac to share');
	});
});

mui('#frame-content').on('tap', '.video-cover', function() {
	var id = this.getAttribute('data-id');
	var video = document.getElementById("video-" + id);
	var video_url = video.src;
	if (plus.networkinfo.getCurrentType() > 3) {
		plus.nativeUI.confirm('饭盒喵检测您正在移动网络下，播放视频需要大量流量喂喵', function(e) {
			if (e.index == 0) {
				if (plus && video_url) {
					if (mui.os.ios) {
						plus.nativeUI.showWaiting("加载链接中", {
							modal: false
						});
						video.onplay = function() {
							plus.nativeUI.closeWaiting();
						};
						video.onclose = function() {
							plus.nativeUI.closeWaiting();
						};
						video.play();
					} else {
						var Intent = plus.android.importClass("android.content.Intent");
						var Uri = plus.android.importClass("android.net.Uri");
						var main = plus.android.runtimeMainActivity();
						var intent = new Intent(Intent.ACTION_VIEW);
						var uri = Uri.parse(video_url);
						intent.setDataAndType(uri, "video/*");
						main.startActivity(intent);
					}
				} else {
					mui.toast("链接可能失效，饭盒喵会尽快处理！");
				}
			}
		}, '确定播放？', ['继续观看', '等会再看']);
	} else {
		if (plus && video_url) {
			if (mui.os.ios) {
				plus.nativeUI.showWaiting("加载链接中", {
					modal: false
				});
				video.onplay = function() {
					plus.nativeUI.closeWaiting();
				};
				video.onclose = function() {
					plus.nativeUI.closeWaiting();
				};
				video.play();
			} else {
				var Intent = plus.android.importClass("android.content.Intent");
				var Uri = plus.android.importClass("android.net.Uri");
				var main = plus.android.runtimeMainActivity();
				var intent = new Intent(Intent.ACTION_VIEW);
				var uri = Uri.parse(video_url);
				intent.setDataAndType(uri, "video/*");
				main.startActivity(intent);
			}
		} else {
			mui.toast("链接可能失效，饭盒喵会尽快处理！");
		}
	}
});